---开奖服务
local skynet = require "skynet"
local cluster = require "skynet.cluster"
local timetool = require "timetool"
local tabletool = require "tabletool"
local filelog = require "filelog"
local base = require "base"
local redisdao = require "redisdao"

local json = require "cjson"
json.encode_sparse_array(true,1,1)

require "cpcqsscenum"

--[[
    重庆时时彩   近 5 期 http://freeagentapi.caim8.com/free?code=ssc_cq 
    重庆时时彩 期号查询 http://freeagentapi.caim8.com/free?code=ssc_cq&qihao=20180422078
--]]
local get_url_address = "http://freeagentapi.caim8.com/free?code=ssc_cq"

local get_open_awards_channels = {
	[1] = {
		--[[
		---免费接口
		index : http://www.caim8.com/index.php
		重庆时时彩   近 5 期 http://freeagentapi.caim8.com/free?code=ssc_cq 
        重庆时时彩 期号查询 http://freeagentapi.caim8.com/free?code=ssc_cq&qihao=20180422078
		--]]
		get_url_address = "http://freeagentapi.caim8.com/free?code=ssc_cq",

		get_all_url = function(curqishu)
			local all_urls = "http://freeagentapi.caim8.com/free?code=ssc_cq"
			all_urls = all_urls .. "&qihao=" .. tostring(curqishu)
			return all_urls
		end,
		parse_points = function(get_result, curqishu)
			local last_get_points = {}
			local status, last_result = skynet.pcall(json.decode, get_result)
            if status == true and last_result and last_result.rows == 2 then
                if curqishu == last_result.data.qihao then
                    local get_points = base.strsplit(last_result.data.data, ",")
                    if #get_points == 5 then
                        for i = 5,1,-1 do
                            table.insert(last_get_points, tonumber(get_points[i]))
                        end
                    end
                end
            end
            return last_get_points
		end,
	},
	--[[
	[2] = {
		--[[
		---付费接口1
		index : http://www.caipiaokong.com/
		http://api.caipiaokong.cn/lottery/?name=cqssc&format=json&uid=1459133&token=cff5f60b3021524794cedb1a4856928431aa94b1
		接口参数:
		name	彩种名称	GET	选填	参考下方（name）参数列表,不填写则显示所购买的全部彩种	
		uid		用户ID	GET	必填	1459133	
		token	通信令牌	GET	必填	cff5f60b3021524794cedb1a4856928431aa94b1
		format	输出格式	GET	选填	json 或 json3 或 xml 或 xml2 或 xml5	
		num		条数设置	GET	选填	10（默认：10条，支持：1~50条）	
		date	日期搜索	GET	选填	20191023	
		order	期号排序	GET	选填	sort（默认为降序，sort为升序）
		--
		get_url_address = "http://api.caipiaokong.cn/lottery/?name",
		get_all_url = function(curqishu)
			local name = "cqssc"
			local format = "json"
			local uid = 1459133
			local token = "cff5f60b3021524794cedb1a4856928431aa94b1"
			local date = ""
			local temps_1 = base.strsplit(curqishu, "-")
			date = date .. tostring(temps_1[1])
			local all_urls = "http://api.caipiaokong.cn/lottery/?name=" ..name .."&format="..format.."&uid="..tostring(uid).."&token="..token
			return all_urls
		end,
		parse_points = function(get_result, curqishu)
			---filelog.sys_error("---------parse_points channel 2-----", get_result, curqishu)
			local last_get_points = {}
			local status, last_result = skynet.pcall(json.decode, get_result)
			---filelog.sys_error("-------status, last_result-------", status, last_result, last_result[curqishu])
			if status == true and last_result then
				if last_result[curqishu] ~= nil and next(last_result[curqishu]) ~= nil then
					local get_points = base.strsplit(last_result[curqishu].number, ",")
					if #get_points == 5 then
						for i = 5,1,-1 do
							table.insert(last_get_points, tonumber(get_points[i]))
						end
					end
				end
			end
			---filelog.sys_error("-------last_get_points-----", last_get_points)
			return last_get_points
		end,
	},
	--]]
	[2] = {
		--[[
			https://d.caijuapi.com/newly?token=qbjretuj2pfwlsag&code=cqssc
			-----
			args 参数
			token	用户账号	付费用户必填，唯一标识。例：token=a1b2c3d4f5	
			code 	彩票代码  部份接口格式支持逗号分割的多种彩票。例：code=cqssc,cqklsf
			rows    返回行数  仅按最新查询时有效，默认5行。例：rows=3 
			issue	查询期数	 仅按最新查询时有效。例：issue=20200101-001
			format	数据格式  支持xml与json格式，默认json。例：format=json
			date 	日期参数  仅按日期查询选中时有效，格式yyyyMMdd或yyyy-MM-dd，低频按年返回。例：date=2015-02-18
			callback  Jsonp回调函数   可选，为jsonp提供支持。例：callback=reader
		--]]
		get_url_address = "https://d.caijuapi.com/newly",
		get_all_url = function(curqishu)
			local all_urls = "https://d.caijuapi.com/newly"
			local token = "qbjretuj2pfwlsag"
			local code = "cqssc"
			local issue = curqishu
			local format = "json"
			local date = ""
			all_urls = all_urls .. "?token=" .. token .. "&code=" .. code
			return all_urls 
		end,
		parse_points = function(get_result, curqishu)
			local last_get_points = {}
			local status, last_result = skynet.pcall(json.decode, get_result)
            if status == true and last_result and last_result.rows == 5 then
            	for index, data_item in pairs(last_result.data) do
                	if curqishu == tostring(data_item.issue) then
                    	local get_points = base.strsplit(data_item.kjcode, ",")
                    	if #get_points == 5 then
                        	for i = 5,1,-1 do
                            	table.insert(last_get_points, tonumber(get_points[i]))
                        	end
                    	end
                	end
                end
            end
            return last_get_points
		end,

	},
}

local function init_get_awardpoint_struct(structs)
	for channel_num, channelinfo in pairs(get_open_awards_channels) do
		if structs[channel_num] == nil then structs[channel_num] = {} end
	end
end

--验证数据的一致性和完整性
local function check_data_is_done(get_data_from_channels)
	local  is_done = true
	---判断是否都拉到数据
	for channel_id, code_data in pairs(get_data_from_channels) do
		if #code_data ~= 5 then is_done = false break end
	end
	if is_done == false then return is_done end
	---判断内容是否一样
	local standstring = ""
	for channel_id, code_data in pairs(get_data_from_channels) do
		local onestring = ""
		for index, data in ipairs(code_data) do
			onestring = onestring .. tostring(data)
		end
		if standstring == "" then
			standstring = onestring
		end
		if standstring ~= onestring then is_done = false break end
	end
	return is_done
end

local filename = "openaward.lua"

local gatenode_is_run = false

local openaward_cache = {}

local openawardlogic = {}


local function get_des_betinfo(betinfos)
    local des_betinfo = ""
    if not betinfos or next(betinfos) == nil then
        return des_betinfo
    end
    local des_table = {}
    for bet_item_id, bet_num in pairs(betinfos) do
        local des_table_bes  = { des = "【".. ECQSSCdesbetid[tonumber(bet_item_id)] .. ", " .. tostring(math.floor( bet_num/ 200)) .. "倍】", bet_item_id = bet_item_id }
        table.insert(des_table, des_table_bes)
    end
    table.sort(des_table, function(first, second)
            if first.bet_item_id < second.bet_item_id then
                return true
            else
                return false
            end
        end)
    for index, desinfo in ipairs(des_table) do
        des_betinfo = des_betinfo .. desinfo.des
    end
    return des_betinfo
end

function openawardlogic.check_url_forbidden()
	local key = "cpcqssc_get_url_forbidden"
	local status, value = redisdao.query_data(".gmmqredis", "get", key)
	--filelog.sys_error("------check_url_forbidden---status, value---", status, value)
	if status and value then
		if tonumber(value) > 0 then
			return true
		else
			return false
		end
	else
		return false
	end
end


function openawardlogic.check_gate_isrun()
	local status, result = skynet.pcall(cluster.call, "gatenode", ".router", "get_online_state")
	if status == true and next(result) ~= nil then
		gatenode_is_run = true
	else
		gatenode_is_run = false
	end
end

function openawardlogic.get_gamename()
	local gamename = "cpcqssc" .. "_diamond"
    return gamename
end

function openawardlogic.create_comment(curqishu)
    local tradeid = skynet.call(".nodeuuid", "lua", "getuuid")
    local now = timetool.get_time()
    local nodename = skynet.getenv("nodename")
    local start_time = timetool.get_time() or 0
	return {table_uuid = tostring(nodename) .. "_" .. tostring(curqishu) .. "_" .. now,
			table_tradeid = tradeid,start_time = start_time,jackpot_id = ""}
end

function openawardlogic.send_mail_to_player(rid, fields)
	local status = skynet.pcall(cluster.send, "gatenode", ".router", "newmail", tonumber(rid), fields)
end

function openawardlogic.send_diamond_to_givesystem(rid, givefields)
	local status = skynet.pcall(cluster.send, "gatenode", ".router", "givemoney", tonumber(rid), givefields)
end


function openawardlogic.write_openawardlog(curqishu, comment, open_before, open_after, system_get, system_back, all_result)
	local cur_record_id = comment.table_uuid .. "_" .. os.date("%Y%m%d_%H%M%S", comment.start_time)
    local tablerecords = {}
    tablerecords.curqishu = curqishu
    tablerecords.open_time = comment.start_time
    tablerecords.open_before_sys_diamond = open_before
    tablerecords.open_after_sys_diamond = open_after
    tablerecords.system_get = system_get
    tablerecords.system_back = system_back
    tablerecords.points = all_result.points
    tablerecords.prize_ids = all_result.prize_ids
    tablerecords.bet_info = all_result.bet_info
    tablerecords.player_get_info = all_result.player_get_info
    tablerecords = json.encode(tablerecords)
    --调用日志服务写到文件
	skynet.send(".tablerecordlog", "lua", "write", cur_record_id, tablerecords)
end

function openawardlogic.write_get_failedlog(curqishu, comment, open_before, open_after, system_get, system_back, all_result)
	local cur_record_id = comment.table_uuid .. "_" .. os.date("%Y%m%d_%H%M%S", comment.start_time)
    local tablerecords = {}
    tablerecords.open_award_is_failed = true
    tablerecords.curqishu = curqishu
    tablerecords.open_time = comment.start_time
    tablerecords.open_before_sys_diamond = open_before
    tablerecords.open_after_sys_diamond = open_after
    tablerecords.system_get = system_get
    tablerecords.system_back = system_back
    tablerecords.points = all_result.points
    tablerecords.prize_ids = all_result.prize_ids
    tablerecords.bet_info = all_result.bet_info
    tablerecords.player_get_info = all_result.player_get_info
    tablerecords.get_open_award_points_channels = all_result.get_open_award_points_channels
    tablerecords = json.encode(tablerecords)
    --调用日志服务写到文件
	skynet.send(".tablerecordlog", "lua", "write", cur_record_id, tablerecords)
end


function openawardlogic.get_system_benefit()
	--[[
	local key = "cpcqssc_benefit"
	local status, value = redisdao.query_data(".gmmqredis", "get", key)
	if value == nil then
		-----设置初始值0
		local status, result = redisdao.query_data(".gmmqredis", "set", key, 0)
		return 0
	else
		return value
	end
	--]]
	local gamename = openawardlogic.get_gamename()
	local status, value = skynet.pcall(skynet.call, ".slotmgr", "lua", "get_system_inventory", gamename)
	if status == true and value ~= nil then
		return value
	else
		return 0
	end
end
---获取系统最大亏损值
function openawardlogic.get_system_lostlimit()
	local key = "cpcqssc_system_lostmax"
	local status, value = redisdao.query_data(".gmmqredis", "get", key)
	if value == nil then
		local setvalue = - 20000 * 100
		local status, result = redisdao.query_data(".gmmqredis", "set", key, setvalue)
		return setvalue
	else
		return tonumber(value)
	end
end

function openawardlogic.update_system_benefit(upvalue, comment)
	local oldvalue = openawardlogic.get_system_benefit()
	local newvalue = oldvalue + upvalue
	--[[
	local key = "cpcqssc_benefit"
	local status, result = redisdao.query_data(".gmmqredis", "set", key, newvalue)
	filelog.sys_error("------update_system_benefit, status, result----", status, result)
	--]]
	local gamename = openawardlogic.get_gamename()
	local status, result = skynet.pcall(skynet.call, ".slotmgr", "lua", "update_system_inventory", gamename, upvalue, comment)
end

---检查系统是否破产
function openawardlogic.check_system_break()
	local is_break = false
	local lostlimit = openawardlogic.get_system_lostlimit()
	local system_benefit = openawardlogic.get_system_benefit()
	if system_benefit < lostlimit then
		is_break = true
	end
	return is_break
end

---请求开奖数据接口
function openawardlogic.query_openaward_data(qi_shu)
	local check_forbidden = openawardlogic.check_url_forbidden()
	if check_forbidden == true then return false end

	local get_result_url = get_url_address .. "&qihao=" .. tostring(qi_shu)
    --local status, result = skynet.pcall(skynet.call, ".httpservice", "lua", "send_http_request", 0, get_result_url)
    local status, request_status, result = skynet.pcall(skynet.call, ".webclient", "lua", "request", get_result_url)
    if not status or not request_status then
        return false
    else
        return result
    end
end

function openawardlogic.query_openaward_data_bychannel(channel_id, qi_shu)
	local check_forbidden = openawardlogic.check_url_forbidden()
	if check_forbidden == true then return false end
	if not channel_id or not get_open_awards_channels[channel_id] then return false end
	local channel_data = get_open_awards_channels[channel_id]
	local get_result_url = channel_data.get_all_url(qi_shu)
	local status, request_status, result = skynet.pcall(skynet.call, ".webclient", "lua", "request", get_result_url)
	if not status or not request_status then
		return false
	else
		return result
	end
end

function openawardlogic.return_betinfo_totable(curqishu)
	if not curqishu then return end
	local award_cache = openaward_cache[curqishu]
	if not award_cache then return end	
	local address = award_cache.tableaddress
	if address and address > 0 then
		local status, result = skynet.pcall(skynet.call, address, "lua", "cmd", "notice_openawards", award_cache.record)
	end
end

--开奖处理函数
function openawardlogic.open_award_deal(tableaddress, curqishu, all_playerbet_info)
	if not tableaddress or not curqishu or not all_playerbet_info then return end
	if curqishu == "" then return end
	---检查系统是否破产
	local is_break = openawardlogic.check_system_break()
	if is_break == true then
		---如果系统破产,返还给下注用户
		local qi_shu_betinfo = "cpcqssc_bet_info:" .. tostring(curqishu)
		local get_status, get_allrids = redisdao.query_data(".gmmqredis", "hkeys", qi_shu_betinfo)
		if get_status == true then
			for index, bet_rid in pairs(get_allrids) do
				local state, bet_detail = redisdao.query_data(".gmmqredis", "hget", qi_shu_betinfo, bet_rid)
				if state == true then
					local temps = base.strsplit(qi_shu_betinfo, ":")
					local curqishu = temps[2]
					openawardlogic.return_bet_deal(curqishu, tonumber(bet_rid), bet_detail)
				end
			end
		end
		---删除缓存数据
		local de_status, de_result = redisdao.query_data(".gmmqredis", "del", qi_shu_betinfo)
		return
	end
	local outoftime = 10 * 60
	----存入缓存
	if openaward_cache[curqishu] == nil then
		openaward_cache[curqishu] = {}
	end
	openaward_cache[curqishu].tableaddress = tableaddress
	openaward_cache[curqishu].curqishu = curqishu
	openaward_cache[curqishu].all_playerbet_info = tabletool.deepcopy(all_playerbet_info)
	openaward_cache[curqishu].record = {
		points = nil,
        prize_ids = nil,
        open_award_time = 0, 
        open_qishu = curqishu,
        bet_info = nil,
        player_get_info = nil,
	}
	local rid_values = {}

	local cache_curqishu = curqishu
	local cache_data = openaward_cache[curqishu]
	local temps_1 = base.strsplit(curqishu, "-")
	if #temps_1 ~= 2 then return end
	local new_qishu = tostring(temps_1[1]) .. tostring(temps_1[2])
	local odds_list_get = skynet.call(".slotmgr", "lua", "get_odds_list")
	local gamename = openawardlogic.get_gamename()
	local status, service_fee_rate = skynet.pcall(skynet.call, ".slotmgr", "lua", "get_service_fee_rate", gamename)
	if status == false then
		service_fee_rate = 0.00
	end
	local qi_shu_betinfo = "cpcqssc_bet_info:" .. tostring(curqishu)
	local curqishu = tostring(temps_1[1]) .. tostring(temps_1[2])
	local get_open_award_points_channels = {}
	local begin_time = timetool.get_time()
	local now_time = timetool.get_time()
	init_get_awardpoint_struct(get_open_award_points_channels)
	local is_done = check_data_is_done(get_open_award_points_channels)
	while (is_done == false and now_time - begin_time < outoftime) do
		for channel_id, struct in pairs(get_open_award_points_channels) do
			---filelog.sys_error("-------struct--------", #struct)
			if #get_open_award_points_channels[channel_id] ~= 5 then
				get_open_award_points_channels[channel_id] = {}
				local get_result = openawardlogic.query_openaward_data_bychannel(channel_id, curqishu)
				if get_result ~= false then
					local points_temp = get_open_awards_channels[channel_id].parse_points(get_result, curqishu)
					----filelog.sys_error("---------points_temp------", channel_id, points_temp)
					if #points_temp == 5 then
						for index, point in ipairs(points_temp) do
							table.insert(get_open_award_points_channels[channel_id], point)
						end
					end
				end
			end
			---filelog.sys_error("---------channel_id-----", channel_id, struct)
        end
        is_done = check_data_is_done(get_open_award_points_channels)
        ---filelog.sys_error("---------get_open_award_points_channels-------", is_done, get_open_award_points_channels)
        skynet.sleep(8 * 100)
        now_time = timetool.get_time()
	end
	---filelog.sys_error("--------get_data_over-----", get_open_award_points_channels)
	local get_open_award_points = {}
	is_done = check_data_is_done(get_open_award_points_channels)
	---filelog.sys_error("------is_done------", is_done)
	if is_done == true then
		get_open_award_points = get_open_award_points_channels[1]
	end
	if #get_open_award_points == 5 then
		---成功获取开奖数据
		local rand_result = skynet.call(".slotmgr","lua","get_lottery_result_by_points", get_open_award_points)
    	local openaward_result = tabletool.deepcopy(rand_result.points)
    	local get_status, get_allrids = redisdao.query_data(".gmmqredis", "hkeys", qi_shu_betinfo)
		local all_player_gets = {}
		local system_get = 0  ---系统获取
		local system_back = 0 ---系统返奖
		local system_benefit = 0 ---系统利润
		if get_status == true then
			for index, bet_rid in pairs(get_allrids) do
				local state, bet_detail = redisdao.query_data(".gmmqredis", "hget", qi_shu_betinfo, bet_rid)
				if state == true then
					local player_betinfo = json.decode(bet_detail)
					if player_betinfo and next(player_betinfo) ~= nil then
						if all_player_gets[bet_rid] == nil then
							all_player_gets[bet_rid] = {
                				details = {},
                				change = 0,
                				real_change = 0,
            				}
						end
						if rid_values[bet_rid] == nil then
							rid_values[bet_rid] = {
								rid = bet_rid,
								real_change = 0,
							}
						end
						for bet_item_id, bet_num in pairs(player_betinfo) do
							for index, prize_id in pairs(rand_result.prize_ids) do
								if tonumber(bet_item_id) == prize_id then
									all_player_gets[bet_rid].details[prize_id] = all_player_gets[bet_rid].details[prize_id] or 0
									all_player_gets[bet_rid].details[prize_id] = all_player_gets[bet_rid].details[prize_id] + bet_num * odds_list_get[prize_id]
									all_player_gets[bet_rid].change = all_player_gets[bet_rid].change + bet_num * odds_list_get[prize_id]
								end
							end
							system_get = system_get + bet_num
							rid_values[bet_rid].real_change = rid_values[bet_rid].real_change - bet_num
						end
						if all_player_gets[bet_rid].change > 0 then
							all_player_gets[bet_rid].real_change = math.floor(all_player_gets[bet_rid].change * (1 - 2 * service_fee_rate) )
						end
						rid_values[bet_rid].real_change = rid_values[bet_rid].real_change + all_player_gets[bet_rid].real_change
						system_back = system_back + all_player_gets[bet_rid].real_change
						openawardlogic.return_award_deal(cache_curqishu, bet_rid, player_betinfo, all_player_gets[bet_rid], rand_result.points)
					end
				end
			end
		end
		system_benefit = system_get - system_back
		openaward_cache[cache_curqishu].record.points = tabletool.deepcopy(rand_result.points)
		openaward_cache[cache_curqishu].record.prize_ids = tabletool.deepcopy(rand_result.prize_ids)
		openaward_cache[cache_curqishu].record.open_award_time = timetool.get_time()
		openaward_cache[cache_curqishu].record.bet_info = tabletool.deepcopy(all_playerbet_info)
		openaward_cache[cache_curqishu].record.player_get_info = tabletool.deepcopy(all_player_gets)
		local before_open = openawardlogic.get_system_benefit()
		local comment = openawardlogic.create_comment(cache_curqishu)
		openawardlogic.update_system_benefit(system_benefit, comment)
		local after_open = openawardlogic.get_system_benefit()
		----发送玩家输赢
		---filelog.sys_error("--------all_players win or lose---------", rid_values, comment)
		local send_status, send_result = skynet.pcall(skynet.call, ".slotmgr", "lua", "send_player_changes", rid_values, comment)
		----写log
		openawardlogic.write_openawardlog(cache_curqishu, comment, before_open, after_open, system_get, system_back, openaward_cache[cache_curqishu].record)
		----删除缓存数据
		local de_status, de_result = redisdao.query_data(".gmmqredis", "del", qi_shu_betinfo)
		----返回开奖数据给桌子
		openawardlogic.return_betinfo_totable(cache_curqishu)
	else
		---filelog.sys_error("-------get_data_failed----------", get_open_award_points_channels)
		---写入拉取数据失败日志
		local before_open = openawardlogic.get_system_benefit()
		local comment = openawardlogic.create_comment(cache_curqishu)
		openawardlogic.update_system_benefit(0, comment)
		local after_open = openawardlogic.get_system_benefit()
		local all_result = {
			points = {},
        	prize_ids = {},
        	open_award_time = timetool.get_time(), 
        	open_qishu = curqishu,
        	bet_info = tabletool.deepcopy(all_playerbet_info),
        	get_open_award_points_channels = get_open_award_points_channels,
		}
		openawardlogic.write_get_failedlog(cache_curqishu, comment, before_open, after_open, 0, 0, all_result)
		---没有获取开奖数据，返还给下注用户
		local get_status, get_allrids = redisdao.query_data(".gmmqredis", "hkeys", qi_shu_betinfo)
		if get_status == true then
			for index, bet_rid in pairs(get_allrids) do
				local state, bet_detail = redisdao.query_data(".gmmqredis", "hget", qi_shu_betinfo, bet_rid)
				if state == true then
					local temps = base.strsplit(qi_shu_betinfo, ":")
					local curqishu = temps[2]
					openawardlogic.return_bet_deal(curqishu, tonumber(bet_rid), bet_detail)
				end
			end
		end
		---删除缓存数据
		local de_status, de_result = redisdao.query_data(".gmmqredis", "del", qi_shu_betinfo)
	end
end

---缓存数据开奖处理函数
function openawardlogic.open_award_deal_cache(qi_shu_betinfo)
	if not qi_shu_betinfo then return end
	---检查系统是否破产，破产就直接把下注返退给玩家
	local is_break = openawardlogic.check_system_break()
	if is_break == true then
		---系统破产,返还给下注用户
		local get_status, get_allrids = redisdao.query_data(".gmmqredis", "hkeys", qi_shu_betinfo)
		if get_status == true then
			for index, bet_rid in pairs(get_allrids) do
				local state, bet_detail = redisdao.query_data(".gmmqredis", "hget", qi_shu_betinfo, bet_rid)
				if state == true then
					local temps = base.strsplit(qi_shu_betinfo, ":")
					local curqishu = temps[2]
					openawardlogic.return_bet_deal(curqishu, tonumber(bet_rid), bet_detail)
				end
			end
		end
		local de_status, de_result = redisdao.query_data(".gmmqredis", "del", qi_shu_betinfo)
		return 
	end

	local outoftime = 10 * 60
	local temps = base.strsplit(qi_shu_betinfo, ":")
	if #temps ~= 2 then return end
	local cache_curqishu = temps[2]
	local temps_1 = base.strsplit(temps[2], "-")
	if #temps_1 ~= 2 then return end
	local odds_list_get = skynet.call(".slotmgr", "lua", "get_odds_list")
	local gamename = openawardlogic.get_gamename()
	local status, service_fee_rate = skynet.pcall(skynet.call, ".slotmgr", "lua", "get_service_fee_rate", gamename)
	if status == false then
		service_fee_rate = 0.00
	end
	local curqishu = tostring(temps_1[1]) .. tostring(temps_1[2])
	local get_open_award_points = {}
	local begin_time = timetool.get_time()
	local now_time = timetool.get_time()
	local open_awardresult = {
		points = nil,
        prize_ids = nil,
        open_award_time = 0, 
        open_qishu = cache_curqishu,
        bet_info = nil,
        player_get_info = nil,
    }
    local rid_values = {}
    local all_playerbet_info = {}
    local all_player_gets = {}
	while #get_open_award_points ~= 5 and now_time - begin_time < outoftime do
		get_open_award_points = {}
		local get_result = openawardlogic.query_openaward_data(curqishu)
		if get_result ~= false then
            local status, last_result = skynet.pcall(json.decode, get_result)
            if status == true and last_result and last_result.rows == 2 then
                if curqishu == last_result.data.qihao then
                    local get_points = base.strsplit(last_result.data.data, ",")
                    if #get_points == 5 then
                        for i = 5,1,-1 do
                            table.insert(get_open_award_points, tonumber(get_points[i]))
                        end
                    end
                end
            end
            if #get_open_award_points == 5 then
            end 
        end
        skynet.sleep(2 * 100)
        now_time = timetool.get_time()
	end
	if #get_open_award_points == 5 then
		---成功获取开奖数据
		local rand_result = skynet.call(".slotmgr","lua","get_lottery_result_by_points", get_open_award_points)
    	local openaward_result = tabletool.deepcopy(rand_result.points)
    	local get_status, get_allrids = redisdao.query_data(".gmmqredis", "hkeys", qi_shu_betinfo)
		local system_get = 0  ---系统获取
		local system_back = 0 ---系统返奖
		local system_benefit = 0 ---系统利润
		if get_status == true then
			for index, bet_rid in pairs(get_allrids) do
				local state, bet_detail = redisdao.query_data(".gmmqredis", "hget", qi_shu_betinfo, bet_rid)
				if state == true then
					local player_betinfo = json.decode(bet_detail)
					if player_betinfo and next(player_betinfo) ~= nil then
						if all_player_gets[bet_rid] == nil then
							all_player_gets[bet_rid] = {
								change = 0,
								real_change = 0,
								details = {},
							}
						end
						if all_playerbet_info[bet_rid] == nil then
							all_playerbet_info[bet_rid] = {}
						end
						if rid_values[bet_rid] == nil then
							rid_values[bet_rid] = {
								rid = bet_rid,
								real_change = 0,
							}
						end
						all_playerbet_info[bet_rid] = tabletool.deepcopy(player_betinfo)
						for bet_item_id, bet_num in pairs(player_betinfo) do
							for index, prize_id in pairs(rand_result.prize_ids) do
								if tonumber(bet_item_id) == prize_id then
									all_player_gets[bet_rid].details[prize_id] = all_player_gets[bet_rid].details[prize_id] or 0
									all_player_gets[bet_rid].details[prize_id] = all_player_gets[bet_rid].details[prize_id] + bet_num * odds_list_get[prize_id]
									all_player_gets[bet_rid].change = all_player_gets[bet_rid].change + bet_num * odds_list_get[prize_id]
								end
							end
							system_get = system_get + bet_num
							rid_values[bet_rid].real_change = rid_values[bet_rid].real_change - bet_num
						end
						if all_player_gets[bet_rid].change > 0 then
							all_player_gets[bet_rid].real_change = math.floor(all_player_gets[bet_rid].change * (1 - 2 * service_fee_rate) )
						end
						rid_values[bet_rid].real_change = rid_values[bet_rid].real_change + all_player_gets[bet_rid].real_change
						system_back = system_back + all_player_gets[bet_rid].real_change
						openawardlogic.return_award_deal(curqishu, bet_rid, player_betinfo, all_player_gets[bet_rid], rand_result.points)
					end
				end
			end
		end
		system_benefit = system_get - system_back
		open_awardresult.points = tabletool.deepcopy(rand_result.points)
		open_awardresult.prize_ids = tabletool.deepcopy(rand_result.prize_ids)
		open_awardresult.open_award_time = timetool.get_time()
		open_awardresult.bet_info = tabletool.deepcopy(all_playerbet_info)
		open_awardresult.player_get_info = tabletool.deepcopy(all_player_gets)
		local before_open = openawardlogic.get_system_benefit()
		local comment = openawardlogic.create_comment(cache_curqishu)
		openawardlogic.update_system_benefit(system_benefit, comment)
		local after_open = openawardlogic.get_system_benefit()
		---发送玩家输赢
		--filelog.sys_error("--------all_players win or lose-cache --------", rid_values, comment)
		local send_status, send_result = skynet.pcall(skynet.call, ".slotmgr", "lua", "send_player_changes", rid_values, comment)
		----写log
		openawardlogic.write_openawardlog(cache_curqishu, comment, before_open, after_open, system_get, system_back, open_awardresult)
		----删除缓存数据
		local de_status, de_result = redisdao.query_data(".gmmqredis", "del", qi_shu_betinfo)
	else
		---没有获取开奖数据，返还给下注用户
		local get_status, get_allrids = redisdao.query_data(".gmmqredis", "hkeys", qi_shu_betinfo)
		if get_status == true then
			for index, bet_rid in pairs(get_allrids) do
				local state, bet_detail = redisdao.query_data(".gmmqredis", "hget", qi_shu_betinfo, bet_rid)
				if state == true then
					local temps = base.strsplit(qi_shu_betinfo, ":")
					local curqishu = temps[2]
					openawardlogic.return_bet_deal(curqishu, tonumber(bet_rid), bet_detail)
				end
			end
		end
		local de_status, de_result = redisdao.query_data(".gmmqredis", "del", qi_shu_betinfo)
	end
end

--服务器重启时从redis拉取下注信息
function openawardlogic.openaward_init()
	while gatenode_is_run == false do
		openawardlogic.check_gate_isrun()
		skynet.sleep(5 * 100)
	end
	local curtime = timetool.get_time()
	local get_curr_qishu = skynet.call(".slotmgr", "lua", "get_curr_qishu_string", curtime)
	local keypattern = "cpcqssc_bet_info:*"
	local status, result = redisdao.query_data(".gmmqredis", "keys", keypattern)
	if not status then return end
	for index, qi_shu_betinfo in pairs(result) do
		local temps = base.strsplit(qi_shu_betinfo, ":")
		if #temps == 2 then
			if tostring(get_curr_qishu) ~= tostring(temps[2]) then
				skynet.fork(openawardlogic.open_award_deal_cache, qi_shu_betinfo)
			end
		end
	end
end

---开奖后发奖函数
function openawardlogic.return_award_deal(curqishu, bet_rid, playerbetinfo, get_info, points)
	if gatenode_is_run == false then return end
	if not curqishu or not bet_rid or not playerbetinfo or not get_info or not points then return end
	if #points ~= 5 then return end
	local pointstring = ""
    for i = 5,1,-1 do
        pointstring = pointstring .. tostring(points[i])
    end
    local nowtime = timetool.get_time()
	if get_info.real_change > 0 then
        local strfmt = "" .. EMailContentAward
        local cur_qishu = curqishu
        local betinfos = get_des_betinfo(playerbetinfo)
        --[[
            第 %s 期开奖号码为%s,您购买了【 %s 】。恭喜你获得彩金 %d 元，请前往银行中领取彩金!
        --]]
        local content = string.format(strfmt, cur_qishu, pointstring,  betinfos, get_info.real_change/100)
        local attachs = {diamond = get_info.real_change}
        local fields = {subject = EMailTitle, content = content }
        openawardlogic.send_mail_to_player(bet_rid, fields)
        ---local tradeid = skynet.call(".nodeuuid", "lua", "getuuid")
        local rid = 0
        local target_rid = tonumber(bet_rid)
        local value = tonumber(get_info.real_change)
        local tmfmt = tostring( os.date("%m%d%H%M%S",nowtime))
        local rndcode = tostring(base.get_random(100000,999999))
        local tradeid = tmfmt .. "_" .. rid .. "_" .. target_rid .. "_" .. value .. "_" .. rndcode
        local givefields = {
            tradeid = tradeid,
            sendname = "系统",
            recvname = "",
            begin_value = 0,
            end_value = 0,
            recvrid = tonumber(bet_rid),
            give_type = EGiveMoneyType.EGIVEMONEY_TYPE_CP_AWARD,
            give_value = tonumber(get_info.real_change),
            current_state = EGiveMoneySate.EGIVEMONEY_STATE_WAIT_DRAW,
            remark = "彩票中奖",
        }
        openawardlogic.send_diamond_to_givesystem(rid, givefields)
	else
		local strfmt = "" .. EMailContentNoAward
        local cur_qishu = curqishu
        local betinfos = get_des_betinfo(playerbetinfo)
        local content = string.format(strfmt, cur_qishu, pointstring, betinfos)
        local fields = {subject = EMailTitle, content = content}
        openawardlogic.send_mail_to_player(bet_rid, fields)
	end
end

---开奖失败退还
function openawardlogic.return_bet_deal(curqishu, bet_rid, playerbetinfo)
	if not curqishu or not bet_rid or not playerbetinfo then return end
	if curqishu == "" or bet_rid < 0 then return end
	local player_betinfo = json.decode(playerbetinfo)
	if next(player_betinfo) == nil then return end
	local all_bet_num = 0
	for bet_item_id, betnum in pairs(player_betinfo) do
		all_bet_num = all_bet_num + betnum
	end
	local strfmt = "" .. EMailContentFail
    local cur_qishu = curqishu
    ---local betinfos = get_des_betinfo(tableobj.all_player_betinfo[rid])
    --[[
       因为重庆时时彩官方数据接口问题，造成我们未能获取到第%s期数据，所以第%s期彩票作废，现全额退还投注金额 %.2f 元，请及时领取！
    --]]
    local content = string.format(strfmt, cur_qishu, cur_qishu, all_bet_num/100)
    local attachs = {diamond = all_bet_num }
    local fields = {subject = EMailTitleGetFail, content = content }
    openawardlogic.send_mail_to_player(bet_rid, fields)
    ---local tradeid = skynet.call(".nodeuuid", "lua", "getuuid")
    local rid = 0
    local nowtime = timetool.get_time()
    local target_rid = tonumber(bet_rid)
    local value = tonumber(all_bet_num/100)
    local tmfmt = tostring( os.date("%m%d%H%M%S",nowtime))
    local rndcode = tostring(base.get_random(100000,999999))
    local tradeid = tmfmt .. "_" .. rid .. "_" .. target_rid .. "_" .. value .. "_" .. rndcode
    local givefields = {
        tradeid = tradeid,
        sendname = "系统",
        recvname = "",
        begin_value = 0,
        end_value = 0,
        recvrid = tonumber(bet_rid),
        give_type = EGiveMoneyType.EGIVEMONEY_TYPE_CP_BACK,
        give_value = tonumber(all_bet_num),
        current_state = EGiveMoneySate.EGIVEMONEY_STATE_WAIT_DRAW,
        remark = "彩票退还",
    }
    openawardlogic.send_diamond_to_givesystem(rid, givefields)
end 

local CMD = {}
---进入开奖流程
function CMD.start_open_award(tableaddress, curqishu, all_playerbet_info)
	skynet.fork(openawardlogic.open_award_deal, tableaddress, curqishu, all_playerbet_info)
end

---返回系统盈利
function CMD.get_system_getmoney()
	-- body
	local system_benefit = openawardlogic.get_system_benefit()
	if not system_benefit then
		return 0
	else
		return system_benefit
	end
end

---返回系统破产值
function CMD.get_system_getlostlimit()
	local system_lostlimit = openawardlogic.get_system_lostlimit()
	if not system_lostlimit then
		return 0
	else
		return system_lostlimit
	end
end

---检查系统是否破产
function CMD.check_system_break()
	local is_break = openawardlogic.check_system_break()
	return is_break
end

---下注时保存下注信息到redis防止服务器重启下注信息丢失
function CMD.save_player_betinfo(curqishu, bet_rid, playerbetinfo)
	if not curqishu or not bet_rid or not playerbetinfo then return false end
	local curtime = timetool.get_time()
	local state, get_curqishu = skynet.pcall(skynet.call, ".slotmgr", "lua", "get_curr_qishu_string", curtime)
	if curqishu ~= get_curqishu or bet_rid == 0 or next(playerbetinfo) == nil then
		return false
	end
	local key = "cpcqssc_bet_info:" .. tostring(curqishu)
	local status, result = redisdao.query_data(".gmmqredis", "hset", key, bet_rid, json.encode(playerbetinfo))
end

skynet.start(function()
	skynet.dispatch("lua",function(session, source, cmd, ...)
        local f = CMD[cmd]
        if f then
            skynet.retpack(f(...))
        else
            skynet.retpack()
        end
    end)
    openawardlogic.openaward_init()
end)